package com.springboot.demo.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * BIO服务处理器
 *
 * @author supu
 * @date 2019-12-03 14:25
 **/
public class BIOServerHandler implements Runnable {
    private Socket socket;

    public BIOServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            printWriter = new PrintWriter(this.socket.getOutputStream(), true);
            String body = null;
            while (true) {
                // 若客户端用的是 writer.print() 传值，那readerLine() 是不能获取值的
                body = bufferedReader.readLine();
                if (body == null) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + ", BIO server receive data:" + body);
                // 返回客户端数据
                printWriter.println(body + " data is received" );
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (this.socket != null) {
                    this.socket.close();
                    this.socket = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
